package router

import (
	"cuelang.org/go/cue/ast"
	"cuelang.org/go/cue/build"
	"cuelang.org/go/cue/parser"
	"encoding/json"
	"gitee.com/hubdev/core/pkg/api/v1x"
	"github.com/yeqown/log"
)

type Builder struct {
	Bi  *build.Instance
	err error
}

func (b *Builder) AddFile(name string, data []byte) {
	if b.err != nil {
		return
	}
	f, err := parser.ParseFile(name, data)
	if err != nil {
		b.err = err
		return
	}
	if err = b.Bi.AddSyntax(f); err != nil {
		b.err = err
		return
	}
}
func (b *Builder) Eval(path string) ([]byte, error) {
	return EvalPath(b.Bi, "outputs")
}

func NewBuilder(f *ast.File) *Builder {
	builder := &Builder{
		Bi: build.NewContext().NewInstance("", nil),
	}
	err := builder.Bi.AddSyntax(f)
	if err != nil {
		builder.err = err
	}
	return builder
}

func Parse(filePath string, datas []byte) (f *ast.File, config *v1x.ConfigSpec, err error) {
	f, err = parser.ParseFile("main.cue", datas)
	if err != nil {
		log.Errorf("[Skip---] parse Bind %s error,reason:%s", filePath, err)
		return
	}
	bd := build.NewContext().NewInstance("", nil)

	if err = bd.AddSyntax(f); err != nil {
		log.Errorf("add main cue fail reason:%s", err)
		return
	}
	var data []byte
	if data, err = EvalPath(bd, "config"); err != nil {
		log.Errorf("get config data error reason:%s", err)
		return
	}
	config = &v1x.ConfigSpec{}
	if err = json.Unmarshal(data, config); err != nil {
		log.Errorf("json parse config error ,reason:%s", err)
		return
	}
	return
}
